<?php

class Request 
{
	public function __construct() 
	{
		
	}
	
	public function getQueryStringParam($paramName) 
	{
		$params = explode('?', $this->getRequestUrl());
		if (count($params) > 0) {
			foreach ($params as $param) {
				$tmp = split('=', $param);
				if (strtolower($tmp[0]) == $paramName) {
					return $tmp[1];
				}
			}
		}
		return null;
	}
	
	public function validate() 
	{
		//TODO: fix when validation will be implemented		
	}
	
	function getParam($name, $default = null)
	{
	    if (array_key_exists($name, $_POST)) {
	    	return $_POST[$name];
	    }
	    return $default;
	}
		
	public function getUriSegment($segment) 
	{
		$segments = explode('/', $this->getQueryString());
		
		if (count($segments) >= $segment) {
			return $segments[$segment];
		}
		return null;
	}
	
	public function getCookie($cookieName) 
	{
		// TODO: fix when cookie will  be implemented
		return null;	
	}
	
	public function getRequestMethod() 
	{
		return strtolower($_SERVER['REQUEST_METHOD']);
	}
	
	public function IsAuthenticated() 
	{
		return false;	
	}
	
	public function IsLocal() 
	{
		return $_SERVER['SERVER_ADDR'] == '127.0.0.1';
	}
	
	public function IsSecureConnection() 
	{
		if (array_key_exists('HTTPS', $_SERVER)) {
			return $_SERVER['HTTPS'] == "on";
		}
		return false;
	}
	
	public function getLogonUser() 
	{
		return false;	
	}
	
	public function getPhysicalApplicationPath() 
	{
		return $_SERVER['DOCUMENT_ROOT'];
	}
	
	public function getQueryString() 
	{
		return $_SERVER['QUERY_STRING'];
	}
	
	public function getServerVariables($varName) 
	{
		if (array_key_exists($varName, $_SERVER)) {
			return $_SERVER[$varName];
		}	
		return null;
	}
	
	public function getRequestUrl() 
	{
		return $_SERVER['REQUEST_URI'];
	}
	
	public function getReferrer() 
	{
		return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
	}
	
	public function getBrowserInfo() 
	{
		return new Browser();
	}
	
	public function getUserIpAddress() 
	{
		if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
	      $ip=$_SERVER['HTTP_CLIENT_IP'];
	    }
	    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
	      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	    }
	    else {
	      $ip=$_SERVER['REMOTE_ADDR'];
	    }
	    
	    return $ip;
	}
	
	public function getUserHostName() {
		return gethostbyaddr($_SERVER['REMOTE_ADDR']);
	}
	
	public function getUserLanguages() {
		$result = array();
		foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
    		$pattern = '/^(?P<primarytag>[a-zA-Z]{2,8})' . 
    					'(?:-(?P<subtag>[a-zA-Z]{2,8}))?(?:(?:;q=)' .
    					'(?P<quantifier>\d\.\d))?$/';

    		$splits = array();
    		
    		if (preg_match($pattern, $lang, $splits)) {
        		$result[] = $splits;
		    }
		}
		return $result;
	}
}

?>